<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总共: {{ total }} 条</span>
        </template>
        <template #right>
          <el-button round size="small" type="warning" @click="$router.push('/employees/import')">导入 Excel</el-button>
          <el-button v-allow="'export_excel'" round size="small" type="danger" @click="hExport">导出 Excel</el-button>
          <el-button round size="small" type="primary" @click="showDialog=true">新增员工</el-button>
        </template>
      </page-tools>
      <el-card style="margin-top: 20px">
        <el-table :data="employees">
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="头像">
            <template v-slot="{ row }">
              <!-- <img class="avatar" :src="row.staffPhoto" alt=""> -->
              <image-holder :src="row.staffPhoto" />
            </template>
          </el-table-column>
          <el-table-column label="工号" prop="workNumber" />
          <!-- <el-table-column label="聘用形式" prop="formOfEmployment" /> -->
          <el-table-column label="聘用形式">
            <template v-slot="{row}">
              {{ formatEmployment(row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" sortable>
            <template v-slot="{row}">
              {{ formatDate(row.timeOfEntry) }}
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template v-slot="{row}">
              <el-button type="text" size="small" @click="$router.push('/employees/detail/' + row.id)">查看</el-button>
              <el-button type="text" size="small" @click="hAssign(row.id)">分配角色</el-button>
              <el-button type="text" size="small" @click="hDel(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
      <div style="height: 60px; margin-top: 10px">
        <el-pagination
          :current-page="q.page"
          :page-sizes="[ 5, 10, 20]"
          :page-size="q.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="hSizeChange"
          @current-change="hCurrentChange"
        />
      </div>
      <!-- 放置 dialog -->
      <el-dialog
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        title="新增员工"
        :visible.sync="showDialog"
        width="45%"
        @close="hCloseDialog"
      >
        <emp-dialog ref="AddEmployee" @close="showDialog=false" @success="hSuccess" />
      </el-dialog>
      <!-- 分配角色 dialog -->
      <el-dialog
        v-if="showDialogRole"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        title="分配角色"
        :visible.sync="showDialogRole"
        width="45%"
      >
        <assign-role :id="curId" @close="showDialogRole=false" />
      </el-dialog>
    </div>
  </div>
</template>
<script>
import { delEmployee, getEmployees } from '@/api/employees'
import employeesConst from '@/constant/employees'
import dayjs from 'dayjs'
// 引入 dialog
import empDialog from './empDialog.vue'
// 引入组件
import AssignRole from './assignRole.vue'

export default {
  components: {
    empDialog,
    AssignRole
  },
  data() {
    AssignRole
    AssignRole
    return {
      employees: [],
      total: 0,
      q: {
        page: 1,
        size: 10
      },
      showDialog: false,
      showDialogRole: false,
      curId: ''
    }
  },
  created() {
    // 调用请求数据函数
    this.loadEmployees()
  },
  methods: {
    async loadEmployees() {
      // 发请求获取员工列表
      const res = await getEmployees(this.q)
      // console.log(res)
      this.total = res.data.total
      this.employees = res.data.rows
    },
    formatEmployment(code) {
      const result = employeesConst.hireType.find(item => item.id === code)
      if (result) {
        return result.value
      } else {
        return '未知'
      }
    },
    hSizeChange(size) {
      this.q.size = size
      this.loadEmployees()
    },
    hCurrentChange(page) {
      this.q.page = page
      this.loadEmployees()
    },
    async hDel(id) {
      try {
      // 先提醒用户
        await this.$confirm('该操作将永久删除员工，请确认是否继续？', '提示', { type: 'warning' })
        // 发请求删除
        const res = await delEmployee(id)
        // 提醒用户
        this.$message.success(res.message)
        // 更新页码
        if (this.employees.length === 1 && this.q.page > 1) {
          this.q.page--
        }
        // 更新列表
        this.loadEmployees()
      } catch (e) {
        if (e === 'cancel') return
        this.$message.error(e.message)
      }
    },
    hSuccess() {
      // 关闭 dialog
      this.showDialog = false
      // 更新页码
      this.total++
      this.q.page = Math.ceil(this.total / this.q.size)
      // 更新数据
      this.loadEmployees()
    },
    formatDate(date) {
      return dayjs(date).format('YYYY-MM-DD')
    },
    hCloseDialog() {
      this.$refs.AddEmployee.resetForm()
    },
    async hExport() {
      const mapInfo = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      // 1. 发请求获取所有的数据
      const res = await getEmployees({ page: 1, size: this.total })
      // console.log(res)
      const list = res.data.rows
      const first = list[0]
      if (!first) return
      // 取出 header
      const header = Object.keys(first).map(enKey => mapInfo[enKey])

      const data = list.map(item => {
        const code = item['formOfEmployment']
        item['formOfEmployment'] = employeesConst.hireType[code]
        return Object.values(item)
      })

      // 2. 导出 Excel (表头英文转中文)
      const excel = await import('@/vendor/Export2Excel')
      excel.export_json_to_excel({
        header, // 表头, 传入一个数组
        data, // 数据, 传入一个二维数组 [ [] ] , 二维数组里面的数组就是一条数据
        filename: '员工数据', // 导出的文件名称
        autoWidth: true, // 自适应宽度
        bookType: 'xlsx' // 文件类型
      })
    },
    hAssign(id) {
      // 开启 dialog
      this.showDialogRole = true
      // 传递 id
      this.curId = id
    }
  }
}
</script>

<style lang="scss" scoped>
.avatar {
  width: 50px;
  height: 50px;
  border-radius: 50%;
}
.el-pagination{
  display: flex;
  justify-content: center;
  align-content: center;
}
</style>
